package utils

import (
	"admin100/library/define"
	"admin100/library/define/defErr"
	"admin100/library/utils/enum"
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os/exec"
	"strings"
)

func ExecShell(s string) string {
	cmd := exec.Command("/bin/bash", "-c", s)
	var (
		out    bytes.Buffer
		stderr bytes.Buffer
	)
	cmd.Stdout = &out
	cmd.Stderr = &stderr
	err := cmd.Run()

	if len(out.String()) == 0 {
		return ""
	}
	if err != nil {
		fmt.Println(stderr.String())
	}
	defErr.IfPanic(err, define.Fail)
	return out.String()
}

//
func HttpRequest(url string, data string) string {
	var result struct {
		ErrorCode int    `json:"error_code"`
		ErrorMsg  string `json:"error_msg"`
	}
	sign := String2md5(data + enum.GmSalt)
	base64Data := base64.URLEncoding.EncodeToString([]byte(data))
	requestBody := "data=" + base64Data + "&sign=" + sign
	resp, err := http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(requestBody))
	defErr.IfPanic(err, define.Fail, "http请求失败")
	defer resp.Body.Close()
	responseBody, err := ioutil.ReadAll(resp.Body)
	defErr.IfPanic(err, define.Fail, "读取http返回内容失败")

	if string(responseBody) == "" {
		return "fail"
	}

	err = json.Unmarshal(responseBody, &result)
	defErr.IfPanic(err, define.Fail, "http返回不是json结构")

	if result.ErrorCode != 0 {
		return result.ErrorMsg
	}
	return result.ErrorMsg
}
